<template>
  <div class="tableRow">
    <el-row class="toolbar">
      <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd"
                 v-permission="'system:menu:add'"> 新增
      </el-button>
      <el-button type="info" icon="el-icon-edit" :disabled="dialog.isBatchEditDisabled" size="mini" plain
                 @click="handleEdit" v-permission="'system:menu:edit'"> 编辑
      </el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="dialog.isBatchRemoveDisabled" size="mini" plain
                 @click="handleBatchDelete" v-permission="'system:menu:remove'"> 删除
      </el-button>
    </el-row>
    <tree-table :columns="columns" :data="data" :operates="operates"
                @handle-selection-change="handleSelectionChange"/>
    <el-dialog :title="dialog.title"
               :visible.sync="dialog.dialogFormVisible"
               :modal-append-to-body="false"
               :destroy-on-close="false"
               @close="closeDialog"
               width="600px">
      <el-form :model="menuModel" ref="menuForm" label-width="100px" :rules="menuFormRules" size="small ">
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="menuModel.menuType" :disabled="dialog.isEdit" @change="typeChange">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentId" v-if="menuModel.menuType!=='M'">
          <!--el-tree-select  文档地址 https://ayiaq1.github.io/el-tree-select/website/#/components/ElTreeSelect-->
          <el-tree-select v-model="menuModel.parentId" :selectParams="dialog.selectParams"
                          :treeParams="dialog.treeParams"
                          @searchFun="searchFun" ref="treeSelect"/>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="menuModel.menuName" placeholder="菜单名称"/>
        </el-form-item>
        <el-form-item label="菜单地址" prop="url" v-if="menuModel.menuType!=='F'">
          <el-input v-model="menuModel.url" placeholder="菜单地址"/>
        </el-form-item>
        <el-form-item label="权限标识" prop="perms" v-if="menuModel.menuType!=='M'">
          <el-input v-model="menuModel.perms" placeholder="权限标识"/>
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="menuModel.orderNum" value="1" :min="1" label="显示顺序"/>
        </el-form-item>
        <el-form-item label="菜单状态" v-if="menuModel.menuType !== 'F'" prop="visible">
          <el-switch v-model="menuModel.visible" active-color="#13ce66" inactive-color="#ff4949"
                     active-text="显示"
                     inactive-text="隐藏"
                     active-value="0"
                     inactive-value="1"/>
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="menuModel.menuType==='M'">
          <e-icon-picker v-model="menuModel.icon"/>
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="menuModel.menuType==='C'">
          <el-input v-model="menuModel.component" placeholder="组件路径"/>
        </el-form-item>
        <el-form-item label="默认路径" prop="redirect" v-if="menuModel.menuType==='M'">
          <el-input v-model="menuModel.redirect" placeholder="默认路径"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="menuModel.remark" placeholder="备注" maxlength="100"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.dialogFormVisible=false" size="medium">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import TreeTable from '@/components/TreeTable/TreeTable.vue';
import {addMenu, checkMenuNameUnique, getMenuTreeData, menuTreeSelectData, removeMenu, updateMenu} from '@/api/menu';
import {validateForm} from '@/utils';

@Component({components: {TreeTable}})
export default class Menu extends Vue {
  private data: Array<any> = [];
  @Ref('menuForm') private menuForm: any;
  @Ref('treeSelect') private treeSelect: any;
  columns: any = [
    {
      label: 'ID',
      prop: 'id',
      width: 150
    },
    {
      label: '名称',
      prop: 'menuName'
    },
    {
      label: '排序',
      prop: 'orderNum'
    },
    {
      label: '菜单地址',
      prop: 'url'
    },
    {
      label: '图标',
      prop: 'icon', render: function (createElement, row) {
        if (row && row.row && row.row.icon) {
          return createElement('eIcon', {
                attrs: {
                  iconName: row.row.icon
                }
              }, ['']
          );
        }
      }
    }, {
      label: '可见', prop: 'visible', sortable: 'custom', render: function (createElement, row) {
        if (row && row.row && row.row.visible === '0') {
          return createElement('el-tag', {
                attrs: {
                  type: 'success'
                }
              }, ['显示']
          );
        } else if (row && row.row && row.row.visible === '1') {
          return createElement('el-tag', {
                attrs: {
                  type: 'warning'
                }
              }, ['隐藏']
          );
        } else {
          return createElement('div', {}, ['']);
        }
      }
    },
    {
      label: '类型',
      prop: 'menuType', render: function (createElement, row) {
        if (row && row.row && row.row.menuType === 'M') {
          return createElement('el-tag', {
                attrs: {
                  type: 'success'
                }
              }, ['目录']
          );
        } else if (row && row.row && row.row.menuType === 'C') {
          return createElement('el-tag', {
                attrs: {
                  type: 'info'
                }
              }, ['菜单']
          );
        } else if (row && row.row && row.row.menuType === 'F') {
          return createElement('el-tag', {
                attrs: {
                  type: 'warning'
                }
              }, ['按钮']
          );
        } else {
          return createElement('el-tag', {
                attrs: {
                  type: 'danger'
                }
              }, ['未知']
          );
        }
      }
    },
    {
      label: '权限标识',
      prop: 'perms'
    }
  ];
  operates: any = {
    width: 200,
    fixed: 'right',
    list: [
      {
        label: '编辑',
        type: 'warning',
        icon: 'el-icon-edit',
        plain: true,
        disabled: (index, row) => {
          return false;
        },
        permission: 'system:menu:edit',
        method: (index, row) => {
          this.handleEdit(index, row);
        }
      },
      {
        label: '删除',
        type: 'danger',
        icon: 'el-icon-delete',
        plain: true,
        disabled: (index, row) => {
          return false;
        },
        permission: 'system:menu:remove',
        method: (index, row) => {
          this.handleDelete(index, row);
        }
      }
    ]
  };
  dialog: any = {
    dialogFormVisible: false,
    title: '对话框',
    isEdit: false,
    isBatchEditDisabled: true,
    isBatchRemoveDisabled: true,
    formData: [],
    selectParams: {
      clearable: true,
      placeholder: '请选择上级菜单'
    },
    treeParams: {
      clickParent: true,
      filterable: true,
      accordion: true,
      data: [],
      props: {
        children: 'children',
        label: 'label',
        disabled: 'disabled',
        value: 'id'
      }
    }
  };
  menuModel: any = {
    parentId: 0,
    orderNum: 1,
    menuType: 'M',
    menuName: '',
    url: '',
    perms: '',
    visible: '0',
    icon: '',
    component: '',
    redirect: '',
    remark: ''
  };
  menuFormRules: any = {
    menuName: [
      {required: true, message: '菜单名称不能为空', trigger: ['blur']},
      {validator: this.validateMenuNameUnique, trigger: 'blur'}
    ], menuType: [
      {required: true, message: '菜单类型不能为空', trigger: ['blur']}
    ], parentId: [
      {required: true, message: '上级菜单不能为空', trigger: ['blur']}
    ], url: [
      {required: true, message: '菜单地址不能为空', trigger: ['blur']}
    ], perms: [
      {required: true, message: '权限标识不能为空', trigger: ['blur']}
    ], orderNum: [
      {required: true, message: '显示排序不能为空', trigger: ['blur']}
    ], visible: [
      {required: true, message: '菜单状态不能为空', trigger: ['blur']}
    ], icon: [
      {required: true, message: '图标不能为空', trigger: ['change']}
    ], component: [
      {required: true, message: '组件路径不能为空', trigger: ['blur']}
    ], redirect: [
      {required: true, message: '默认路径不能为空', trigger: ['blur']}
    ]
  };


  /*新增*/
  handleAdd(): void {
    this.dialog.title = '添加菜单';
    this.dialog.isEdit = false;
    menuTreeSelectData().then((response: any) => {
      this.menuModel.menuType = 'M';
      this.menuModel.orderNum = 1;
      if (response.data) {
        this.dialog.treeParams.data = response.data;
      }
      this.dialog.dialogFormVisible = true;
    }).catch((e) => {
      console.log(e);
    });
  }


  /*编辑*/
  handleEdit(index: number, row: any): void {
    this.dialog.title = '编辑菜单';
    this.dialog.isEdit = true;
    menuTreeSelectData().then((response: any) => {
      this.menuModel = Object.assign({}, row || this.dialog.formData[0]);
      if (response.data) {
        this.dialog.treeParams.data = response.data;
      }
      this.dialog.dialogFormVisible = true;
    }).catch((e) => {
      console.log(e);
    });
  }

  /*删除*/
  handleDelete(index, row) {
    this.$confirm('确定要删除该选项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      return removeMenu({'ids': [row.id]});
    }).then((response: any) => {
      this.getData();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.log(e);
    });
  }

  submitForm(): void {
    this.menuForm.validate((valid: boolean) => {
      if (valid) {
        switch (this.menuModel.menuType) {
          case 'M':
            this.menuModel.component = 'Layout';
            this.menuModel.parentId = 0;
            delete this.menuModel['perms'];
            break;
          case 'C':
            delete this.menuModel['redirect'];
            delete this.menuModel['icon'];
            break;
          case 'F':
            delete this.menuModel['url'];
            delete this.menuModel['icon'];
            delete this.menuModel['component'];
            delete this.menuModel['redirect'];
            break;
        }
        delete this.menuModel.children;

        if (this.dialog.isEdit) {
          //编辑
          updateMenu(this.menuModel).then((response: any) => {
            this.getData();
            this.reset();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            console.log(e);
            validateForm(e.data, this.menuForm, this.menuFormRules);
          });
        } else {
          //新增
          addMenu(this.menuModel).then((response: any) => {
            this.getData();
            this.reset();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            console.log(e);
            validateForm(e.data, this.menuForm, this.menuFormRules);
          });
        }
      }
    });
  }

  /*验证菜单名称是否唯一*/
  validateMenuNameUnique(rule: any, value: any, callback: any) {
    checkMenuNameUnique({
      menuName: value,
      id: this.menuModel.id,
      parentId: this.menuModel.parentId
    }).then((res: any) => {
      if (res.data && res.data === '0') {
        callback();
      } else {
        callback(new Error('菜单已经存在'));
      }
    }).catch((err: any) => {
      console.log(err);
      callback(new Error('菜单已经存在'));
    })
  }

  /*选中事件*/
  handleSelectionChange(val): void {
    if (val) {
      this.dialog.isBatchRemoveDisabled = val.length <= 0;
      this.dialog.isBatchEditDisabled = val.length !== 1;
    }
    this.dialog.formData = val;
  }

  /*批量删除*/
  handleBatchDelete() {
    //删除
    this.$confirm('确定要删除选定选项？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const ids: Array<any> = [];
      this.dialog.formData.forEach((item, index) => {
        ids[index] = item.id;
      });
      return removeMenu({'ids': ids});
    }).then((response: any) => {
      this.getData();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.log(e);
    });
  }

  getData() {
    getMenuTreeData().then(response => {
      this.data = response.data;
    }).catch((e) => {
      console.log(e);
    });
  }


  /*重置表单*/
  reset(): void {
    this.menuModel = {
      parentId: 0,
      orderNum: 1,
      menuType: '',
      menuName: '',
      url: '',
      perms: '',
      visible: '0',
      icon: '',
      component: '',
      redirect: '',
      remark: ''
    };
    (this as any).resetForm('menuForm');
  }

  /*关闭对话框*/
  closeDialog() {
    this.$nextTick(() => {
      this.reset();
    });
  }

  searchFun(value: any): void {
    this.treeSelect.filterFun(value);
  }

  typeChange(val) {
    this.$nextTick(() => {
      this.reset();
      this.menuModel.menuType = val;
    });
  }

  activated() {
    this.getData();
  }
}
</script>

<style scoped lang="scss">

</style>

